from datetime import date
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser

from django.utils import timezone

from users.models import User
from orders.models import OrderInfo


# Create your views here.


class UserTotalCountView(APIView):
    """
    用户总数统计
    """
    # 返回的数据不是模型类里面的数据，所有不用序列化器，直接用APIView

    # 当前视图接口只有is_staff=True才能访问
    # permission_classes = [IsAdminUser]

    def get(self, request):
        # 1.统计出注册的用户总数量
        count = User.objects.count()
        # 2.获取当前时间
        cur_time = timezone.localtime() # 返回配置里面的上海时间当前时间 2021-1-8 10:11:23 +80:00 Asia/Shanghai
        # timezone.now() # utc当前时间
        print('cur_time', cur_time)
        return Response({
            'count': count,
            'date': cur_time.date() # 只保留年月日
        })


class UserDayCountView(APIView):
    """
    日增用户数量统计
    """
    def get(self, request):
        # 1.获取当日0时刻
        cur_time = timezone.localtime() # 当前时间， 有时区
        cur_0_time = cur_time.replace(hour=0, minute=0, second=0) # 0时刻，保留了时区， django会自动转化为0时区，用于和数据库里面拿出来的数据对比
        # 2.过滤统计
        count = User.objects.filter(
            date_joined__gte = cur_0_time # 用户创建时间大于等于0时刻
        ).count()

        return Response({
            'count': count,
            'data': cur_0_time.date()
        })

class UserActiveCountView(APIView):
    """
    日活跃用户数量统计
    """
    def get(self, request):
        cur_time = timezone.localtime()
        cur_0_time = cur_time.replace(hour=0, minute=0, second=0)
        # 登录时间大于等于当日0时刻
        count = User.objects.filter(
            last_login__gte = cur_0_time
        ).count()

        return Response({
            'count': count, 
            'date': cur_0_time.date()
        })



class UserOrderCountView(APIView):
    """
    日下单用户数量统计
    """
    def get(self, request):
        # 需求：统计当日下了订单关联用户的数量
        # 1.已知条件：当日的0时刻（订单的条件， 属于从表）
        # 2.目标数据：用户数量（主表数据）
        # 总结：使用从表的已知条件，过滤出主表的目标数据

        cur_time = timezone.localtime()
        cur_0_time = cur_time.replace(hour=0, minute=0, second=0)

        # 方案1：从表入手
        # orders = OrderInfo.objects.filter(
        #     create_time__gte = cur_0_time
        # )
        # user_set = set() # 用集合自动去重
        # for order in orders:
        #     user=order.user
        #     user_set.add(user)
        # count = len(user_set) # 集合的长度就是用户数量

        # 方案2：主表入手
        users = User.objects.filter(
            orders__create_time__gte = cur_0_time
        )
        count = len(set(users))

        return Response({
            'count': count,
            'date': cur_0_time.date()
        })

from datetime import timedelta
class UserMonthCountView(APIView):
    """
    月增用户数量统计：包括当天在内，最近30天其中每一天注册用户数量
    """
    def get(self, request):
        # 1.获取当日0时刻, 30天的最后一天的0时刻
        cur_time = timezone.localtime()
        end_0_time = cur_time.replace(hour=0, minute=0, second=0)
        # 2.起始日期的0时刻
        # start_0_time =  end_0_time  -  (统计天数 - 1)
        start_0_time = end_0_time - timedelta(days=29)

        data  = []
        # 3.从起始时间start_0_time开始，遍历获取30天中的每一天的0时刻用于统计
        for index in range(30):
            # calc_0_time = start_0_time + timedelta(days=0)   index=0
            # calc_0_time = start_0_time + timedelta(days=1)   index=1
            # calc_0_time = start_0_time + timedelta(days=2)   index=2
            # .......
            # calc_0_time = start_0_time + timedelta(days=29)  index=29
            # 公式：calc_0_time = start_0_time + timedelta(days=index)

            # 其中某一天的用于计算的0时刻
            calc_0_time = start_0_time + timedelta(days=index)
            # 次日的0时刻
            # 2021-1-6 0:0:0 +8:00  =  2021-1-5 0:0:0 +8:00 + 1天
            next_0_time = calc_0_time + timedelta(days=1)

            count = User.objects.filter(
                date_joined__gte = calc_0_time, # 大于等于某一天的0时刻
                date_joined__lt = next_0_time  # 小于次日的0时刻
            ).count()
            data.append({
                'count': count, 
                'date': calc_0_time.date()
            })

        return Response(data)


from rest_framework.generics import ListAPIView
from meiduo_admin.serializers.home_serializers import *
from goods.models import GoodsVisitCount
class GoodsDayView(ListAPIView):
    """
    日分类商品访问量
    """
    queryset  = GoodsVisitCount.objects.all()
    serializer_class = GoodsVisitCountModelSerializer
    
    def get_queryset(self):
        # 获取当日0时刻
        cur_0_time = timezone.localtime().replace(hour=0, minute=0, second=0)
        # 对类属性queryset查询集进一步过滤
        return self.queryset.filter(create_time__gte=cur_0_time)

